import React, { Component } from 'react';
import E from 'wangeditor'
import request from '@/utils/request';
import { IMG_URL } from '../../utils/utils';

class App extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      editorContent: ''
    }
  }
  render() {
    return (
      <div className="App">
        <div ref="editorElem" style={{textAlign: 'left'}}>
        </div>
        <button onClick={this.clickHandle.bind(this)}>获取内容</button>
        <div dangerouslySetInnerHTML = {{ __html:this.state.editorContent }}>
        </div>
      </div>
    );
  }
  componentDidMount() {
    const elem = this.refs.editorElem
    const editor = new E(elem)
    editor.customConfig.onchange = html => {
      this.setState({
        editorContent: html
      })
    }
    editor.customConfig.customUploadImg = function (files, insert) {
      console.log(files.length)
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name',timestamp3+""+files[0].name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${files[0].name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', files[0]);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          if(xhr.responseText.indexOf("Error")!=-1){
              alert(xhr.responseText.indexOf("Error"))
          }else{
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              insert(IMG_URL + response.filename)
            } else {
              alert('服务器异常');
            }
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法

      // 上传代码返回结果之后，将图片插入到编辑器中

    }
    editor.create()
  }
  clickHandle() {
    alert(this.state.editorContent)
  }
}

export default App;
